package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private DistrictInfoService districtInfoService;
    @Autowired
    private RoomInfoService roomInfoService;

    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    /**
     * todo:实现逻辑：
     *          涉及表：公寓表，图片表，公寓-配套关系表，公寓-标签关系表，公寓-杂费关系表
     *          公寓表，一行数据关系，直接保存或更新
     *          其他表，多行数据关系，不能直接保存或更新
     *          多行修改 = 删除 + 保存
     *      实现步骤：
     *          根据对象中id是否存在，判定执行的操作：
     *          对公寓，基本信息，执行saveOrUpdate操作
     *          如果修改，需先批量删除四个中间表（update,is_delelted = 1）
     *          最后，进行四个中间表的批量保存
     *
     * @return
     */
    @Override
    public void customSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        //根据对象中id是否存在，判定是否执行更新：
        boolean is_update = apartmentSubmitVo.getId() != null;
        //设置省、市、区的名称
        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());

        //对公寓，基本信息，执行saveOrUpdate操作
        saveOrUpdate(apartmentSubmitVo);

        //如果更新，根据条件，删除四个中间表相关数据
        if(is_update){
            //根据公寓id、图片所属对象类型是公寓（1公寓，2房间），删除图片
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,apartmentSubmitVo.getId());
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphInfoLambdaQueryWrapper);

            //根据公寓id，删除公寓-配套关系
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper=new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
            //根据公寓id，删除公寓-标签关系
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper=new LambdaQueryWrapper<>();
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,apartmentSubmitVo.getId());
            apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
            //根据公寓id，删除公寓-杂费值关系
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper=new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        }

        //最后，批量保存中间表数据
        //批量保存图片表数据
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if(!CollectionUtils.isEmpty(graphVoList)){
            List<GraphInfo> graphInfoList =new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }

        //批量保存公寓-杂费关系数据
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if(!CollectionUtils.isEmpty(feeValueIds)){
            List<ApartmentFeeValue> feeValueList=new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .feeValueId(feeValueId)
                        .build();
                feeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(feeValueList);
        }
        //批量保存公寓-标签关系
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if(!CollectionUtils.isEmpty(labelIds)){
            List<ApartmentLabel> apartmentLabelList=new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .labelId(labelId)
                        .build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }
        //批量保存公寓-配套关系
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if(!CollectionUtils.isEmpty(facilityInfoIds)){
            List<ApartmentFacility> apartmentFacilityList =new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .facilityId(facilityInfoId)
                        .build();
                apartmentFacilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }
    }

    /**
     * 根据动态条件条件，分页，多表查询，公寓信息列表
     * 涉及多表嵌套查询，使用mybatis方案，自定义service层，mapper层
     * @param page
     * @param queryVo
     */
    @Override
    public void customPage(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customSelectList(page,queryVo);
    }

    /**
     * todo:根据ID获取公寓详细信息，包含：公寓基本信息，图片列表，配套列表，杂费列表，标签列表
     *     根据业务，需要返回嵌套结果，因此自定义service
     *     1.根据id，查询公寓基本信息，单表
     *     2.根据公寓id，查询图片信息列表，单表,(定义mapper方法和mapper方法调用)
     *     以下涉及多表连接查询，mybatis自定义mapper层
     *     3.根据公寓id，查询公寓配套列表，多表：公寓-配套关系表，配套信息表，mybatis自定义mapper
     *     4.根据公寓id，查询公寓杂费列表，多表：公寓-杂费值关系表，杂费值表，杂费名表
     *     5.根据公寓id，查询公寓标签列表，多表：公寓标签关系表，标签表
     *todo:注意：
     *          1.根据所属对象id，所属对象类型，查询图片列表
     *             常用，所以不使用条件构造器，提取出来 ，自定义maapper层
     *          2.自定义mapper层方法时，当前service，注入自定义mapper还是自定义service？
     *          解决：
     *              如自定义service只有一句调用mappper，不需自定义service方法,直接注入mapper层组件
     * @param id
     * @return
     */
    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        //1.根据id，查询公寓基本信息，单表
        ApartmentInfo apartmentInfo = getById(id);
        //2.根据公寓id,所属对象类型，查询图片信息列表，单表
        List<GraphVo> graphInfoList= graphInfoMapper.selectGraphInfoVoList(id,ItemType.APARTMENT);
        //3.根据公寓id，查询公寓配套列表，多表：公寓-配套关系表，配套信息表，mybatis自定义mapper
        List<FacilityInfo> facilityInfoList=facilityInfoMapper.customSelectList(id);
        //4.根据公寓id，查询公寓杂费列表，多表：公寓-杂费值关系表，杂费值表，杂费名表
        List<FeeValueVo> feeValueVoList = feeValueMapper.customSelectList(id);
        //5.根据公寓id，查询公寓标签列表，多表：公寓标签关系表，标签表
        List<LabelInfo> labelInfoList = labelInfoMapper.customSelectList(id);
        //将公寓详情信息封装apartmentDetailVo进对象
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        apartmentDetailVo.setGraphVoList(graphInfoList);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);
        //返回apartmentDetailVo
        return apartmentDetailVo;
    }

    /**
     * todo:根据id删除公寓信息，
     *      有房间删除失败，
     *      无则，并删除公寓信息，并删除中间表的数据，
     *      涉及表：公寓表，图片表，公寓-配套关系表，公寓-标签关系表，公寓-杂费关系表
     *todo:注意：
     *       删除公寓，同时要删除关联表数据，避免孤儿数据，
     *       但公寓有多个房间，不能直接删公寓，没有房间，才可以删除公寓
     *       因此，有房间，删除失败，
     * @param id
     */
    @Override
    public void customRemoveById(Long id) {
        //查找公寓对应房间数
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(roomInfoLambdaQueryWrapper);
        //如果有房间，
        if(count>0){
            //将失败信息封装进自定义异常，并抛出，被异常处理器捕获并响应Result
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR.getMessage(),ResultCodeEnum.DELETE_ERROR.getCode());
        }

        //如果没有房间，删除公寓以及中间表对应数据：

        //根据id,删除公寓信息
        removeById(id);
        //根据公寓id、图片所属对象类型是公寓（1公寓，2房间），删除图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

        //根据公寓id，删除公寓-配套关系
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper=new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
        //根据公寓id，删除公寓-标签关系
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper=new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
        //根据公寓id，删除公寓-杂费值关系
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper=new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);

    }
}




